package main

import (
	"bufio"
	"fmt"
	"net"
)

var talk chan string
var group []net.Conn

func chart(talk <-chan string) {
	for {
		select {
		case data := <-talk:
			fmt.Println("read succed")
			for _, item := range group {
				item.Write([]byte(data))
			}
		default:
		}
	}
}

//处理函数
func process(conn net.Conn, talk chan<- string) {
	defer conn.Close()
	for {
		reader := bufio.NewReader(conn)
		var buf [128]byte
		n, err := reader.Read(buf[:])
		if err != nil {
			fmt.Println("read from client failed,err:", err)
			return
		}
		recvStrt := string(buf[:n])
		fmt.Println("收到client端发来的数据", recvStrt)
		select {
		case talk <- recvStrt:
			fmt.Println("xiru succed")
		default:
		}
	}
}

func main() {
	listener, err := net.Listen("tcp", "127.0.0.1:6666")
	if err != nil {
		fmt.Println("listen err,err:", err)
		return
	}

	talk = make(chan string, 100)
	for {
		conn, err := listener.Accept()
		if err != nil {
			fmt.Println("accept err,err:", err)
			return
		}

		group = append(group, conn)
		go process(conn, talk)
		go chart(talk)
	}
}
